package org.example.back.controller.user;

import org.example.back.entity.user.UserSleep;
import org.example.back.service.user.UserSleepService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpSession;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/userSleep")
public class UserSleepController {

    @Autowired
    private UserSleepService userSleepService;

    // 新增睡眠记录，自动绑定当前用户ID
    @PostMapping("/save")
    public String saveUserSleep(@RequestBody UserSleep userSleep, HttpSession session) {
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            return "请先登录";
        }
        userSleep.setUserId(userId);
        userSleepService.saveUserSleep(userSleep);
        return "睡眠记录保存成功";
    }

    // 按天查询睡眠记录，从 Session 获取 userId
    @GetMapping("/getByDate")
    public UserSleep getUserSleepByDate(@RequestParam String sleepDate, HttpSession session) {
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            return null;  // 也可以抛异常或返回错误
        }
        return userSleepService.getUserSleepByDate(userId, LocalDate.parse(sleepDate));
    }

    // 查询最近7天睡眠记录，从 Session 获取 userId
    @GetMapping("/getLastWeek")
    public List<UserSleep> getUserSleepLastWeek(HttpSession session) {
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            return List.of(); // 返回空列表或抛异常
        }
        return userSleepService.getUserSleepLastWeek(userId);

    }

    // 查询最近1个月睡眠按周汇总，从 Session 获取 userId
    @GetMapping("/getByWeekInMonth")
    public List<Map<String, Object>> getUserSleepByWeekInMonth(HttpSession session) {
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            return List.of();
        }
        return userSleepService.getUserSleepByWeekInMonth(userId);
    }
}
